<template>
    <div class="box">
      <div class="header">
        <input type="text" placeholder="输入" v-model="content">
        <button @click="pubContent">发布</button>
      </div>
      <ul>
        <li v-for="(item, index) in datas" :key="item.id">
          <span>{{ item.content }}</span>
          <div>
            <span class="del" @click="del(index)">删除</span>
          </div>
        </li>
      </ul>
    </div>
  </template>
  
  <script setup>
  import { ref, watch, onMounted } from 'vue'
  const content = ref('')
  const datas = ref([])
  
  onMounted(() => {
    console.log('onMounted');
    let results = JSON.parse(localStorage.getItem('comments') ? localStorage.getItem('comments') : '[]')
    datas.value = results
  })
  
  // 删除内容
  const del = (index) => {
    if (confirm(`确认删除[${datas.value[index].content}]吗`)) {
      datas.value.splice(index, 1)
    }
  }
  
  // 发布内容
  const pubContent = () => {
    datas.value.push({ id: Date.now(), content: content.value })
    // 清空输入框
    content.value = ''
  }
  
  // 监听datas数据源的改变
  watch(datas, (newV) => {
    console.log('watch');
    // 持久化到本地存储
    localStorage.setItem('comments', JSON.stringify(newV))
  },{deep: true})
  
  </script>
  
  <style scoped>
  * {
    padding: 0;
    margin: 0;
  }
  
  .box {
    width: 300px;
    margin: 50px auto;
  }
  
  
  
  .box .header {
    display: flex;
  }
  
  .box .header button {
    flex-grow: 1;
  }
  
  li {
    display: flex;
    justify-content: space-between;
    list-style-type: none;
  }
  
  li .del {
    color: blue;
    cursor: pointer;
  }
  </style>